package com.zeedev.flyingsaucer.service;

import android.content.ContentQueryMap;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import com.google.inject.Inject;
import com.zeedev.flyingsaucer.global.UfoClubApp;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv.Beers;
import mobi.zeedev.flyingsaucer.common.DataModule.Util;
import mobi.zeedev.flyingsaucer.common.WebLinkModule.interfaces.IndividualBeerQuery;
import roboguice.service.RoboIntentService;
import roboguice.util.Ln;

import java.util.Map;

public class BeerKnurdService2 extends RoboIntentService {

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Service Commands
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    public static final String SERVICE_COMMAND = "BEERKNURDSERVICE2_SERVICE_COMMAND";
    public static final String SERVICE_LAZY_REQUEST = "SERVICE_LAZY_REQUEST";

    public static final String SERVICE_BROADCAST = "BEERKNURDSERVICE2_SERVICE_BROADCAST";
    //Results
    public static final String SERVICE_HOMEINFO_UPDATED = "SERVICE_HOMEINFO_UPDATED";
    public static final String SERVICE_BEERLIST_UPDATED = "SERVICE_BEERLIST_UPDATED";
    public static final String SERVICE_STORELIST = "SERVICE_STORELIST";
    public static final String SERVICE_QUERYING = "SERVICE_QUERYING";
    public static final String SERVICE_IS_QUERYING = "SERVICE_IS_QUERYING";
    public static final String SERVICE_FAILURE = "SERVICE_FAILURE";

    public enum Command {
        REFRESH_BEERS,
        LOGIN,
        STORE_LIST,
        NOTHING,
        REFRESH_EXTRA_BEER_INFO
    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // variables
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    public static final String TAG = "BeerKnurdService2";

    @Inject
    UfoClubApp app;

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // functions
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Inject
    public BeerKnurdService2() {
        super(TAG);
    }


    @Override
    public void onCreate() {
        super.onCreate();


    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    private Boolean isQuerying() {
        return querying;
    }

    private boolean querying = false;

    @Override
    public void onStart(Intent intent, int startId) {

        if (intent.hasExtra(BeerKnurdService2.SERVICE_IS_QUERYING) && isQuerying()) {
            Intent intentIsQuerying = new Intent();
            intentIsQuerying.setAction(SERVICE_BROADCAST);
            intentIsQuerying.putExtra(SERVICE_IS_QUERYING, true);
            this.sendStickyBroadcast(intentIsQuerying);
        }

        super.onStart(intent, startId);


    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);

    }

    @Override
    protected void onHandleIntent(Intent intent) {
//		Log.d(TAG,"On handle intent: " + intent.toString());

        //this.getsetRunningIntent(intent);
        //this.getsetLastRequest(Calendar.getInstance().getTime());
        querying = true;

        Command curCommand = (Command) (intent.hasExtra(SERVICE_COMMAND) ? intent.getSerializableExtra(SERVICE_COMMAND) : Command.NOTHING);
//		Log.d(TAG,"Intent command: " + (curCommand!=null ? curCommand : "<no intent>"));

        switch (curCommand) {
/*//			case LOGIN:
//				Debug.startMethodTracing("getLogin");
//				getLogin();
//				Debug.stopMethodTracing();
//				break;
			case REFRESH_BEERS:
//				Debug.startMethodTracing("refreshBeers");
//				refreshBeers();
//				Debug.stopMethodTracing();
				break;
				
			case STORE_LIST:
//				getStoreList();*/
//
//				break;
            case REFRESH_EXTRA_BEER_INFO:
//				Debug.startMethodTracing("refreshExtraInfo");
                this.refreshExtraBeerInfo();
//				Debug.stopMethodTracing();
                break;
            case NOTHING:
            default:
                break;

        }
        querying = false;


    }


    private void startBackgroundGetExtraBeerInfo() {
        Intent intent = new Intent(this, BeerKnurdService2.class);
        intent.putExtra(BeerKnurdService2.SERVICE_COMMAND, Command.REFRESH_EXTRA_BEER_INFO);
        this.startService(intent);
    }


    /*
     public static void startBackgroundGetExtraBeerInfo(Activity act) {
         Intent intent = new Intent(act,BeerKnurdService2.class);
         intent.putExtra(BeerKnurdService2.SERVICE_COMMAND, Command.REFRESH_EXTRA_BEER_INFO);
         act.startService(intent);
     }*/

    @Inject
    IndividualBeerQuery ibq;

    private void refreshExtraBeerInfo() {
        Ln.i("Starting refresh sequence for updating beer info.");

        Cursor c = app.getContentResolver().query(
                Beers.CONTENT_URI,
                new String[]{Beers.BEER_ID, Beers.BEERS_KEY, Beers.DESCRIPTION, "ifnull(" + Beers.DESCRIPTION + ",'') != '' as " + "beer_valid"},
                "beer_valid" + " = 0 ",
                null,
                null);

        int total = c.getCount();
        Ln.d("Cursor size: " + c.getCount());
//		Log.d(TAG,"Cursor: " + DatabaseUtils.dumpCursorToString(c));
//		Log.d(TAG,"Cursor:" + c.toString());
        ContentQueryMap ccc = new ContentQueryMap(c, Beers.BEER_ID, false, null);
//		Log.d(TAG,"ContentQueryMap:" + ccc.toString());
        Map<String, ContentValues> curIncompleteBeers = ccc.getRows();
//		Log.d(TAG,"curIncompleteBeers:" + curIncompleteBeers.toString());
//        IndividualBeerQueryImpl ibq = new IndividualBeerQueryImpl();

        int res = 0;
        try {
            for (String curBeerId : curIncompleteBeers.keySet()) {

//                ibq.loadRawData(Integer.parseInt(curBeerId));
////				Log.d(TAG,"Raw Data: " + ibq.getRawData());
//                ContentValues ccur = ibq.getContentValue();
//				Log.d(TAG,"res before:" + res);
                Integer curBeerIdInt = null;
                try {
                    curBeerIdInt = Integer.parseInt(curBeerId);
                } catch (Exception e) {
                    Ln.w(e,"Could not parse integer.");
                }

                if (curBeerIdInt != null) {
                    ContentValues ccur = ibq.getContentValue(curBeerIdInt);

                    res += getContentResolver().update(Beers.CONTENT_URI, ccur, Beers.BEER_ID + "=?", Util.asAr(ccur.getAsString(Beers.BEER_ID)));
                    if (res > 20) {
                        break;
                    }

                }


//				Log.d(TAG,"res after:" + res);
//				Log.d(TAG,"Current Loaded Content Values:"+ccur.toString());
            }
        } catch (Exception e) {
            Ln.e(e);
            return;
        }

        if ((total - res) > 0) {
            startBackgroundGetExtraBeerInfo();
        } else {
            app.setLoadedExtraBeerInfo(true);
        }

    }


}
